package com.ctakit.sdk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.Security;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by andyhome on 17-8-23.
 */
public class AESPKCS7Utils {

    static {
      //  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //java 后台开发需要打开这个
    }
    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 16;
    // private static final int saltLength = 16;
    private static final int CACHE_SIZE = 1024;

    private static byte[] mySalt = "61XMvMKJu39UZM6c".getBytes();




   /* private  static  byte[]  getSalt(){
        if(mySalt==null){
            SecureRandom random = new SecureRandom();
            byte[] salt = new byte[saltLength];
            random.nextBytes(salt);
            mySalt = salt;
        }
       return mySalt ;
    }*/

    private static byte[] getSalt() {

        return mySalt;
    }

    public static String encrypt(String cleartext,String password) throws Exception {
        SecretKey secureKey = deriveKeySecurely(password, KEY_SIZE);


        byte[] result = encryptData(cleartext.getBytes(), getSalt(), secureKey);
        return toHex(result);
    }


    private static byte[] encryptData(byte[] data, byte[] iv, SecretKey key) {
        return encryptOrDecrypt(data, key, iv, true);
    }


    private static byte[] decryptData(byte[] data, byte[] iv, SecretKey key) {
        return encryptOrDecrypt(data, key, iv, false);
    }

    public static String decrypt(String encrypted,String password) throws Exception {
        SecretKey insecureKey = deriveKeySecurely(password, KEY_SIZE);

        byte[] result = decryptData(toByte(encrypted), getSalt(), insecureKey);

        return new String(result);
    }


    private static SecretKey deriveKeyInsecurely(String password, int keySizeInBytes) {
        byte[] passwordBytes = password.getBytes(Charset.forName("UTF-8"));
        return new SecretKeySpec(
                InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(passwordBytes, keySizeInBytes), ALGORITHM);
    }


    private static SecretKey deriveKeySecurely(String password, int keySizeInBytes) {


        // Use this to derive the key from the password:
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), getSalt(), 100 /* iterationCount */, keySizeInBytes * 8 /* key size in bits */);
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
            return new SecretKeySpec(keyBytes, ALGORITHM);
        } catch (Exception e) {
            throw new RuntimeException("Deal with exceptions properly!", e);
        }
    }


    private static byte[] encryptOrDecrypt(
            byte[] data, SecretKey key, byte[] iv, boolean isEncrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
            cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key,
                    new IvParameterSpec(iv));
            return cipher.doFinal(data);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("This is unconceivable!", e);
        }
    }

    private static String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    private static String fromHex(String hex) {
        return new String(toByte(hex));
    }

    private static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        return result;
    }

    private static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private final static String HEX = "0123456789ABCDEF";

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }


    /**
     * <p>
     * 文件加密
     * </p>
     *
     * @param password
     * @param sourceFilePath
     * @param destFilePath
     * @throws Exception
     */
    public static void encryptFile(String sourceFilePath, String destFilePath,String password) throws Exception {
        File sourceFile = new File(sourceFilePath);
        if (sourceFile.exists() && sourceFile.isFile()) {
            InputStream in = new FileInputStream(sourceFile);
            encryptFile(in, destFilePath,password);
        }
    }


    public static void encryptFile(InputStream in, String destFilePath,String password) {

        File destFile = new File(destFilePath);
        OutputStream out = null;
        CipherInputStream cin = null;
        try {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }

            destFile.createNewFile();


            out = new FileOutputStream(destFile);

            SecretKey secureKey = deriveKeySecurely(password, KEY_SIZE);

            Cipher cipher = encryptOrDecryptFile(secureKey, getSalt(), true);

            cin = new CipherInputStream(in, cipher);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = cin.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (cin != null) {
                try {
                    cin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }

    }


    /**
     * <p>
     * 文件解密
     * </p>
     *
     * @param password
     * @param sourcePath
     * @param destFilePath
     * @throws Exception
     */
    public static void decryptFile(String sourcePath, String destFilePath,String password) throws Exception {
        File sourceFile = new File(sourcePath);

        if (sourceFile.exists() && sourceFile.isFile()) {
            InputStream in = new FileInputStream(sourceFile);
            decryptFile(password, in, destFilePath);
        }


    }


    public static void decryptFile(String password, InputStream in, String destFilePath) {
        File destFile = new File(destFilePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        } else {
            if (destFile.exists()) {
                destFile.delete();
            }
        }
        FileOutputStream out = null;
        CipherOutputStream cout = null;
        try {
            destFile.createNewFile();

            out = new FileOutputStream(destFile);

            SecretKey secureKey = deriveKeySecurely(password, KEY_SIZE);
            Cipher cipher = encryptOrDecryptFile(secureKey, getSalt(), false);

            cout = new CipherOutputStream(out, cipher);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                cout.write(cache, 0, nRead);
                cout.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();


        } finally {
            if (cout != null) {
                try {
                    cout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }

    }


    private static Cipher encryptOrDecryptFile(SecretKey key, byte[] iv, boolean isEncrypt) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
            cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));


            return cipher;
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("This is unconceivable!", e);
        }
    }


    /**
     * 不能直接在main 函数运行，要在android 环境运行，
     * @param args
     */
    public static void main(String[] args) {

        try {

            String password = "com.sina.com" ;
            String a = AESPKCS7Utils.encrypt("你好中国",password);
            System.out.print(a);
            System.out.print(AESPKCS7Utils.decrypt(a,password));

            //    AESUtils.encryptFile(getContext().getAssets().open("gotoapp.html"), MyFileUtil.getCacheDir(getContext()) + "/mljr.data",password);
            //   AESUtils.decryptFile(MyFileUtil.getCacheDir(getContext()) + "/mljr.data", MyFileUtil.getCacheDir(getContext()) + "/mljr.html",password);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}